package com.mdd.admin.service.order.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.mdd.admin.service.order.IAccountLogService;
import com.mdd.admin.validate.common.PageParam;
import com.mdd.admin.validate.order.AccountLogParam;
import com.mdd.admin.vo.order.AccountLogListVo;
import com.mdd.admin.vo.order.AccountLogDetailVo;
import com.mdd.admin.vo.order.RechargeOrderListVo;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.order.AccountLog;
import com.mdd.common.entity.order.RechargeOrder;
import com.mdd.common.enums.AccountChangeEnum;
import com.mdd.common.mapper.order.AccountLogMapper;
import com.mdd.common.utils.ArrayUtil;
import com.mdd.common.utils.StringUtil;
import com.mdd.common.utils.TimeUtil;
import com.mdd.common.utils.UrlUtil;
import com.mdd.common.config.GlobalConfig;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.*;

/**
 * 用户账户记录实现类
 * @author panweiliang
 */
@Service
public class AccountLogServiceImpl implements IAccountLogService {
        
    @Resource
    AccountLogMapper accountLogMapper;

    /**
     * 用户账户记录列表
     *
     * @author panweiliang
     * @param pageParam 分页参数
     * @param params 搜索参数
     * @return PageResult<AccountLogListVo>
     */
    @Override
    public PageResult<AccountLogListVo> list(PageParam pageParam, Map<String, String> params) {
        Integer page  = pageParam.getPageNo();
        Integer limit = pageParam.getPageSize();

        MPJQueryWrapper<AccountLog> mpjQueryWrapper = new MPJQueryWrapper<AccountLog>()
                .selectAll(AccountLog.class)
                .select("user.sn as userSn, user.nickname as nickname, user.id as userId, user.avatar as avatar, user.mobile as mobile ")
                .innerJoin("?_user user ON user.id=t.user_id".replace("?_", GlobalConfig.knowledgePaymentTablePrefixe))
                .orderByDesc(Arrays.asList("t.id"));

        if (StringUtil.isNotEmpty(params.get("keyword"))) {
            String keyword = params.get("keyword");
            mpjQueryWrapper.nested(wq->wq
                    .like("user.sn", keyword).or()
                    .like("user.nickname", keyword).or()
                    .like("user.mobile", keyword));
        }

        accountLogMapper.setSearch(mpjQueryWrapper, params, new String[]{
                "like:sn@t.sn:str",
                "=:changeType@t.change_type:int",
                "datetime:startTime-endTime@t.create_time:str",
        });


        IPage<AccountLogListVo> iPage = accountLogMapper.selectJoinPage(new Page<>(page, limit), AccountLogListVo.class, mpjQueryWrapper);

        for(AccountLogListVo item : iPage.getRecords()) {
            item.setCreateTime(TimeUtil.timestampToDate(item.getCreateTime()));
            item.setUpdateTime(TimeUtil.timestampToDate(item.getUpdateTime()));
            item.setAvatar(UrlUtil.toAbsoluteUrl(item.getAvatar()));
            item.setChageTypeStr(changeTypeMsg(item.getChangeType()));
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), iPage.getRecords());
    }


    private String changeTypeMsg(int changeType) {

        if (changeType == AccountChangeEnum.BNW_DEC_ADMIN.getCode()) {
            return AccountChangeEnum.BNW_DEC_ADMIN.getMsg();
        } else if (changeType == AccountChangeEnum.BNW_DEC_ORDER.getCode()) {
            return AccountChangeEnum.BNW_DEC_ORDER.getMsg();
        } else if (changeType == AccountChangeEnum.BNW_INC_REFUND.getCode()) {
            return AccountChangeEnum.BNW_INC_REFUND.getMsg();
        } else if (changeType == AccountChangeEnum.BNW_INC_ADMIN.getCode()) {
            return AccountChangeEnum.BNW_INC_ADMIN.getMsg();
        } else if (changeType == AccountChangeEnum.BNW_INC_RECHARGE.getCode()) {
            return AccountChangeEnum.BNW_INC_RECHARGE.getMsg();
        } else {
            return AccountChangeEnum.BNW_INC_RECHARGE_GIVE.getMsg();
        }

    }

    /**
     * 用户账户记录详情
     *
     * @author panweiliang
     * @param id 主键参数
     * @return AccountLog
     */
    @Override
    public AccountLogDetailVo detail(Integer id) {
        AccountLog model = accountLogMapper.selectOne(
                new QueryWrapper<AccountLog>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在");

        AccountLogDetailVo vo = new AccountLogDetailVo();
        BeanUtils.copyProperties(model, vo);
        return vo;
    }

    /**
     * 用户账户记录新增
     *
     * @author panweiliang
     * @param accountLogParam 参数
     */
    @Override
    public void add(AccountLogParam accountLogParam) {
        AccountLog model = new AccountLog();
        model.setSn(accountLogParam.getSn());
        model.setUserId(accountLogParam.getUserId());
        model.setChangeType(accountLogParam.getChangeType());
        model.setAction(accountLogParam.getAction());
        model.setChangeAmount(accountLogParam.getChangeAmount());
        model.setLeftAmount(accountLogParam.getLeftAmount());
        model.setAssociationSn(accountLogParam.getAssociationSn());
        model.setRemark(accountLogParam.getRemark());
        model.setFeature(accountLogParam.getFeature());
        model.setCreateTime(System.currentTimeMillis() / 1000);
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        accountLogMapper.insert(model);
    }

    /**
     * 用户账户记录编辑
     *
     * @author panweiliang
     * @param accountLogParam 参数
     */
    @Override
    public void edit(AccountLogParam accountLogParam) {
        AccountLog model = accountLogMapper.selectOne(
                new QueryWrapper<AccountLog>()
                    .eq("id",  accountLogParam.getId())
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        model.setId(accountLogParam.getId());
        model.setSn(accountLogParam.getSn());
        model.setUserId(accountLogParam.getUserId());
        model.setChangeType(accountLogParam.getChangeType());
        model.setAction(accountLogParam.getAction());
        model.setChangeAmount(accountLogParam.getChangeAmount());
        model.setLeftAmount(accountLogParam.getLeftAmount());
        model.setAssociationSn(accountLogParam.getAssociationSn());
        model.setRemark(accountLogParam.getRemark());
        model.setFeature(accountLogParam.getFeature());
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        accountLogMapper.updateById(model);
    }

    /**
     * 用户账户记录删除
     *
     * @author panweiliang
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        AccountLog model = accountLogMapper.selectOne(
                new QueryWrapper<AccountLog>()
                    .eq("id", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        accountLogMapper.delete(new QueryWrapper<AccountLog>().eq("id", id));
    }

}
